package com.ylsk.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ylsk.common.config.MinioConfig;
import com.ylsk.common.config.SnowIdConfig;
import com.ylsk.common.exception.ServiceException;
import com.ylsk.common.utils.FileUploadUtils;
import com.ylsk.common.utils.MinioUtil;
import com.ylsk.common.utils.StringUtils;
import com.ylsk.common.utils.spring.SpringUtils;
import com.ylsk.system.domain.BusinessFile;
import com.ylsk.system.domain.FileInfo;
import com.ylsk.system.domain.FileSimple;
import com.ylsk.system.mapper.BusinessFileMapper;
import com.ylsk.system.mapper.FileInfoMapper;
import com.ylsk.system.service.IMinioFileService;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Minio 文件存储
 *
 * @author ysy
 * @date 2023/7/26
 */
@Primary
@Service
public class MinioFileServiceImpl implements IMinioFileService {

    private static MinioConfig minio = SpringUtils.getBean(MinioConfig.class);
    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private BusinessFileMapper businessFileMapper;

    @Autowired
    private SnowIdConfig snowIdConfig;


    @Override
    public FileSimple upload(MultipartFile file, String systemType) throws Exception {
        //校验文件
        FileUploadUtils.checkFile(file);
        //生成文件路径
        String filePath = FileUploadUtils.getFilePath(file);
        minioUtil.uploadFile(file,minio.getBucketName(), filePath);

        //文件后缀
        String fileSuffix = FilenameUtils.getExtension(file.getOriginalFilename());

        //创建数据实体对象 将数据进行持久化
        final long snowId = snowIdConfig.getSnowId();
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileId(snowId);
        fileInfo.setFileName(file.getOriginalFilename());
        fileInfo.setFileSize(file.getSize());
        fileInfo.setBucketName(minio.getBucketName());
        fileInfo.setFilePath(filePath);
        fileInfo.setCreateTime(new Date());
        fileInfo.setUpdateTime(new Date());
        fileInfo.setDelFlag("0");
        fileInfo.setSystemType(systemType);
        fileInfo.setFileSuffix(fileSuffix);
        fileInfoMapper.insert(fileInfo);

        //设置返回参数
        FileSimple fileSimple = new FileSimple();

        buildFileSimpleData(fileSimple,fileInfo);

        //String ffmpegGetScreenshot = ffmpegGetScreenshot(file);
        //System.out.println("封面：" + ffmpegGetScreenshot);
        return fileSimple;
    }


    @Override
    public String getFileUrl(FileInfo file) {
        return minioUtil.getFileUrl(file.getBucketName(),file.getFilePath(),minio.getExpires());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeFile(FileInfo file) {
        //删除文件
        minioUtil.removeFile(file.getBucketName(), file.getFilePath());
        //删除文件信息
        int i = fileInfoMapper.deleteById(file.getFileId());
        return i;
    }

    @Override
    public List<FileSimple> getFileListByBusinessId(Long businessId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("model_id",businessId);
        queryWrapper.eq("del_flag",0);
        List<BusinessFile> businessFileList = businessFileMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(businessFileList)){
            return Lists.newArrayList();
        }
        List<Long> fileIds = businessFileList.stream().map(BusinessFile::getFileId).collect(Collectors.toList());
        //查询相关附件信息
        List<FileInfo> fileInfoList = fileInfoMapper.selectBatchIds(fileIds);
        List<FileSimple> fileSimpleList = Lists.newArrayList();

        if(!CollectionUtils.isEmpty(fileInfoList)){
            for (FileInfo fileInfo : fileInfoList) {
                FileSimple fileSimple = new FileSimple();
                buildFileSimpleData(fileSimple,fileInfo);
                fileSimpleList.add(fileSimple);
            }
        }
        return fileSimpleList;
    }

    @Override
    public List<FileSimple> getFileListInBusinessId(List<Long> businessId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("model_id",businessId);
        queryWrapper.eq("del_flag",0);
        List<BusinessFile> businessFileList = businessFileMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(businessFileList)){
            return Lists.newArrayList();
        }
        // todod
        return Lists.newArrayList();
    }

    @Override
    public FileSimple getFile(Long fileId) {
        if(null == fileId){
            throw new ServiceException("附件id不能为空!");
        }
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        if(null == fileInfo){
            throw new ServiceException(String.format("业务数据不存在,businessId=%1$s", fileId));
        }
        FileSimple fileSimple = new FileSimple();
        buildFileSimpleData(fileSimple,fileInfo);
        return fileSimple;
    }

    @Override
    public InputStream getInputStreamFile(Long fileId,String filePath) {
        if(StringUtils.isEmpty(filePath)){
            throw new ServiceException(String.format("业务数据不存在,fileId=%1$s", fileId));
        }
        return minioUtil.getFile(minio.getBucketName(),filePath);
    }


    /**
     * 构建附件数据
     */
    private void buildFileSimpleData(FileSimple fileSimple,FileInfo fileInfo){
        if(null == fileSimple || fileInfo == null) return;
        String fileUrl = minio.getUrl()+"/"+minio.getBucketName()+"/"+fileInfo.getFilePath();
        fileSimple.setFileId(fileInfo.getFileId());
        fileSimple.setSystemType(fileInfo.getSystemType());
        fileSimple.setFileBucket(minio.getBucketName());
        fileSimple.setFileName(fileInfo.getFileName());
        fileSimple.setFilePath(fileInfo.getFilePath());
        fileSimple.setFileUrl(fileUrl);
        fileSimple.setFileSuffix(fileInfo.getFileSuffix());
        fileSimple.setPreviewFileUrl(minioUtil.getFileUrl(minio.getBucketName(),fileInfo.getFilePath()));
    }

//    public String ffmpegGetScreenshot(MultipartFile file) throws IOException {
//        File tofile = new File(file.getOriginalFilename());
//        FileUtils.copyInputStreamToFile(file.getInputStream(),tofile);
//        String absolutePath = tofile.getAbsoluteFile().getAbsolutePath();
//        Map<String, Object> screenshot = VideoUtil.getScreenshot(absolutePath);
//        String imgPath =(String) screenshot.get("imgPath");
//        return imgPath;
//    }
}

